<template>
  <a-modal
    class="common-modal"
    :title="title"
    :footer="null"
    :width="550"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :maskClosable="false"
    style="top: 5%"
  >
    <a-spin :spinning="confirmLoading">
      <a-form
        :model="formState"
        @validateFields="handleOk"
        ref="formRef"
        layout="vertical"
        class="common-modal-content"
      >
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.bridgeRoadNo')"
              name="code"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input
                v-model:value.trim="formState.code"
                disabled
                :placeholder="$t('deviceManage.autoGenerate')"
              />
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.startBridgePoint')"
              name="alineStationId"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                {
                  required: true,
                  message: $t('deviceManage.startBridgePoint'),
                },
              ]"
            >
              <a-select
                v-model:value.trim="formState.alineStationId"
                show-search
                :filterOption="filterOption"
                :options="birdList"
                @change="handleChange1"
              />
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.endBridgePoint')"
              name="blineStationId"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                {
                  required: true,
                  message: $t('deviceManage.endBridgePoint'),
                },
              ]"
            >
              <a-input-group compact>
                <a-select
                  v-model:value.trim="formState.blineStationId"
                  show-search
                  :filterOption="filterOption"
                  :options="birdList"
                  @change="handleChange2"
                  style="width: 70%"
                />
                <a-button
                  type="primary"
                  @click="getRoadList"
                  style="width: 30%"
                  >{{ $t("other.seePath") }}</a-button
                >
              </a-input-group>
            </a-form-item>
          </a-col>

<!--                <a-col :span="18" style="width: 70%">
              <a-form-item label="结束桥接点" name="blineStationId" :labelCol="labelCol" :wrapperCol="wrapperCol" :rules="[{ required: true, message: '结束桥接点!' }]" style="margin-left: 11%;" >
                <a-select v-model:value.trim="formState.blineStationId"  show-search :filterOption="filterOption" :options="birdList" @change="handleChange2"/>
              </a-form-item>
            </a-col>
            <a-col :span="6" class="" style="width: 20%">
              <a-form-item label="" name="blineStationId" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                <span><a-button type="primary" @click="getRoadList">查询路径</a-button></span>
              </a-form-item>
            </a-col>-->
          <a-col :span="24">
            <a-form-item
              :label="$t('deviceManage.path')"
              name="direction"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                { required: true, message: $t('other.pleaseSelectPath') },
              ]"
            >
              <a-select
                v-model:value="formState.direction"
                allowClear
                :placeholder="$t('common.pleaseSelect')"
              >
                <a-select-option
                  v-for="(item, i) in roadList"
                  :value="item.direction"
                  :key="i"
                  >{{ item.direction }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item
              :label="$t('common.startState')"
              name="status"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :rules="[
                { required: true, message: $t('sysManage.selectEnable') },
              ]"
            >
              <a-radio-group v-model:value="formState.status">
                <a-radio
                  v-for="(item, index) in selectOptions.status"
                  :value="item.value"
                  :key="index"
                  >{{ item.label }}</a-radio
                >
              </a-radio-group>
            </a-form-item>
          </a-col> 
        </a-row>
      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{
          $t("common.cancel")
        }}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{
          $t("common.ok")
        }}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="addDialog">
import { nextTick, ref, onBeforeMount } from "vue";
import axios from "@/utils/request";
import { cloneDeep, isEmpty } from "lodash";
import { message } from "ant-design-vue";
import i18n from "@/locales/index";
const { t } = i18n.global;
const emits = defineEmits(['ok'])
const labelCol = { xs: { span: 24 }, sm: { span: 23 } }
const wrapperCol = { xs: { span: 24 }, sm: { span: 23 } }
let title = ref('')
let visible = ref(false)
let isEdit = ref(false)
let confirmLoading = ref(false)
const selectOptions = ref({})
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
let roadList = ref([])
let birdList = ref([])
let objSelect1 = ref({})
let objSelect2 = ref({})

const getRoadList = async () => {
  try {
    let params = doParam()
    if (!isEmpty(params)){
      confirmLoading.value = true
      const res = await axios.postAction('/api/device/bridge-path/calculate-bridge-path', params)
      confirmLoading.value = false
      if (res.success) {
        if (!isEmpty(res.data)){
          res.data.forEach((item,index)=>{
            let arr2 = []
            item.bridgePathDetails && item.bridgePathDetails.forEach(i=>{
              arr2.push(i.lineNo + "-" + i.masterTrackNo + "-" + i.lineStationNo)
            })
            item.direction = arr2.join('->') || ''
            item.indexValue = index+1
          })
        }
        roadList.value = res.data
        confirmLoading.value = false
      }
    }
  } catch (err) {
    console.log(err);
    confirmLoading.value = false;
  }
};

const filterOption = (val, option) => {
  return option.value.toLowerCase().indexOf(val.toLowerCase()) >= 0;
};
//桥接参数
const handleChange1 = async (val,object1) => {
  objSelect1.value = object1
  formState.value.direction = ""
  roadList.value = []
}
const handleChange2 = async (val,object1) => {
  objSelect2.value = object1
  formState.value.direction = ""
  roadList.value = []
}

const edit = async (record, editable) => {
  //获取所有的桥接点
  const res = await axios.getAction('/api/device/hanger-line-bridge/get-all-bridge-station')
  if (res.success){
    if (!isEmpty(res.data)){
      res.data.forEach((i)=>{
        return  i.value = i.lineNo + "-" + i.masterTrackNo + "-"+i.lineStationNo }
      )
    }
    birdList.value = res.data || [];
  }
  initModalData(record, editable)
  await nextTick()
  formRef.value.resetFields()
  formState.value = cloneDeep(record)
  if (!isEmpty(formState.value)){
    formState.value.alineStationId = formState.value.startLineNo +"-"+formState.value.startMasterTrackNo +"-"+ formState.value.startLineStationNo
    formState.value.blineStationId = formState.value.endLineNo +"-"+formState.value.endMasterTrackNo +"-"+ formState.value.endLineStationNo
    formState.value.direction = arrToStr(formState.value.bridgePathDetails)
    await obj(formState.value)
    await getRoadList()
  }
}
const initModalData = (record, editable) => {
  title.value = t('other.editBridge')
  recordInfo.value = Object.assign({}, record);
  visible.value = true;
  isEdit.value = editable;
};

const handleOk = async () => {
  try {
    const values = await formRef.value.validateFields();

    if (!isEmpty(roadList.value)){
      let obj = roadList.value.filter(i=>i.direction == values.direction)
      if (!isEmpty(obj)){
        let params = cloneDeep(obj[0])
        let obj1 = doParam()
        if (!isEmpty(obj1)){
          obj1.bridgePathDetails = params.bridgePathDetails  || []
          obj1.id = formState.value.id
          obj1.status = formState.value.status

          const res = await axios.postAction('/api/device/bridge-path/update', obj1)
          if (res.success) {
            emits("ok");
            confirmLoading.value = false; // 刷新
            visible.value = false;
            initModalStatus();
            message.success(this.$t("common.doSuccess"));
          }
        }
      } else {
        message.error(t("other.startAndEndBridgeNull"));
      }
    } else {
      message.error(t("other.pathNotFound"));
    }
  } catch (err) {
    console.log("0000000", err);
  }
  confirmLoading.value = false;
};

// 处理参数
const obj = (item) => {
  objSelect1.value = {
    lineId: item.startLineId,
    lineNo: item.startLineNo,
    masterTrackId: item.startMasterTrackId,
    masterTrackNo: item.startMasterTrackNo,
    lineStationId: item.startLineStationId,
    lineStationNo: item.startLineStationNo,
    value:
      item.startLineNo +
      "-" +
      item.startMasterTrackNo +
      "-" +
      item.startLineStationNo,
  };
  objSelect2.value = {
    lineId: item.endLineId,
    lineNo: item.endLineNo,
    masterTrackId: item.endMasterTrackId,
    masterTrackNo: item.endMasterTrackNo,
    lineStationId: item.endLineStationId,
    lineStationNo: item.endLineStationNo,
    value:
      item.endLineNo +
      "-" +
      item.endMasterTrackNo +
      "-" +
      item.endLineStationNo,
  };
};

const arrToStr = (item) => {
  let stringValue = "";
  if (!isEmpty(item)) {
    let arr2 = [];
    item &&
      item.forEach((i) => {
        arr2.push(i.lineNo + "-" + i.masterTrackNo + "-" + i.lineStationNo);
      });
    stringValue = arr2.join("->") || "";
  }
  return stringValue;
};

const doParam = () => {
  let params = {};
  if (!isEmpty(objSelect1.value) && !isEmpty(objSelect2.value)) {
    const objStart = cloneDeep(objSelect1.value);
    const objEnd = cloneDeep(objSelect2.value);
    params.startLineId = objStart.lineId;
    params.startMasterTrackId = objStart.masterTrackId;
    params.startLineStationId = objStart.lineStationId;
    params.endLineId = objEnd.lineId;
    params.endMasterTrackId = objEnd.masterTrackId;
    params.endLineStationId = objEnd.lineStationId;
  }
  return params;
};

const handleCancel = () => {
  visible.value = false;
  initModalStatus();
};
const initModalStatus = () => {
  confirmLoading.value = false;
  formState.value = {};
  formRef.value.resetFields();
  objSelect1.value = {};
  objSelect2.value = {};
  roadList.value = [];
  birdList.value = [];
};
const initSelectOptions = (obj) => {
  selectOptions.value = obj
}
onBeforeMount(async () => {
  // console.log("editDialog");
});
defineExpose({
  edit,
  initSelectOptions,
});
</script>
